package com.vcg.comment.support.clean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vcg.comment.support.clean.data.YunCleanJsonData;
import com.vcg.comment.support.clean.utils.HttpClientUtil;
import com.vcg.comment.support.clean.utils.SignVerify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wuyu on 2016/5/31.
 */
@Component
public class FilterComment implements InitializingBean {
    // 云净网api地址
    private final String API_URL = "http://api.yunclean.cn:8080/audit";
    // 签名与验签工具类
    private final SignVerify sv = new SignVerify();

    private String publicKey;

    private String privateKey;

    private final String app_id = "201605253683";

    private Logger logger = LoggerFactory.getLogger(FilterComment.class);

    @Autowired
    private RestTemplate restTemplate;

    public boolean doFilter(YunCleanJsonData jsonData) {


        jsonData.setPublish_date(new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date()));
        // app_id需要云净网进行分配，在调用时替换成您实际申请的app_id

        // 获取当前时间字符串-格式如：“2015-01-01 12:30:00”
        String timestamp = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date());
        // 需要签名的数据，格式如：“201509100001,2015-01-01 12:30:00”
        String sign_string = app_id + "," + timestamp;
        // 获取您自己的私钥
        // 用你的私钥对sign_string进行签名
        String sign = sv.sign(privateKey, sign_string);
        String json_data = jsonData.toString();

        //post的参数需要urlencode，由于httpclient组件里使用了UrlEncodedFormEntity组织参数，所以此处不能编码
        MultiValueMap parameters = new LinkedMultiValueMap();
        parameters.add("app_id", app_id);
        parameters.add("timestamp", timestamp);
        parameters.add("version", "1.1");
        parameters.add("sign", sign);
        parameters.add("json_data", json_data);

        try {
            JSONObject result = restTemplate.postForObject(API_URL, parameters, JSONObject.class);
            // String result = HttpClientUtil.post(API_URL, parameters);
            if (result != null) {

                JSONObject json =  JSON.parseObject(result.getString("json"));
                if (json == null || json.getIntValue("code") != 1001) {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("connenct yunclean error!");
        }
        //防止 Yunclean 出问题影响评论系统,如果有异常 全部以true返回
        return true;
    }

    /**
     * 辅助方法，获取云净网公钥字符串
     *
     * @return
     * @throws Exception
     */
    private String getPublicKey() throws Exception {
        // 读取图普公钥open_tuputech_com_public_key.pem
        ClassPathResource resource = new ClassPathResource("pem/yunclean_public_key.pem");
        InputStream inputStream = resource.getInputStream();
        String publicKeyStr = readKey(inputStream);
        inputStream.close();
        return publicKeyStr;
    }

    /**
     * 辅助方法，获取用户私钥字符串
     *
     * @return
     * @throws Exception
     */
    private String getPrivateKey() throws Exception {
        // 读取你的密钥pkcs8_private_key.pem
        ClassPathResource resource = new ClassPathResource("pem/500px_private_key.pem");
        InputStream inputStream = resource.getInputStream();
        String privateKeyStr = readKey(resource.getInputStream());
        inputStream.close();
        return privateKeyStr;
    }

    private String readKey(InputStream in) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null) {
            if (readLine.charAt(0) == '-') {
                continue;
            } else {
                sb.append(readLine);
                sb.append('\r');
            }
        }
        return sb.toString();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            publicKey = getPublicKey();
            privateKey = getPrivateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
